"""
订单相关定时任务
"""
import logging
from datetime import datetime, timedelta
from sqlalchemy.orm import Session

from utils.database import SessionLocal
from Models.travel.models import Order
from Models.travel.payment_models import Payment, PaymentStatus
from Views.home.websocket.ws_notifier import notify_order_status_change

logger = logging.getLogger(__name__)


def cancel_expired_orders():
    """
    自动取消超时未支付的订单
    检查创建时间超过15分钟且状态仍为pending的订单，自动取消
    """
    db: Session = SessionLocal()
    try:
        # 计算15分钟前的时间
        expire_time = datetime.now() - timedelta(minutes=15)
        
        # 查询超时且未支付的订单
        expired_orders = db.query(Order).filter(
            Order.status == "pending",
            Order.created_at <= expire_time
        ).all()
        
        cancelled_count = 0
        for order in expired_orders:
            try:
                old_status = order.status
                order.status = "cancelled"
                order.updated_at = datetime.now()
                
                # 同时关闭该订单相关的未完成支付记录
                pending_payments = db.query(Payment).filter(
                    Payment.order_id == order.id,
                    Payment.status.in_([PaymentStatus.PENDING.value, PaymentStatus.PROCESSING.value])
                ).all()
                
                for payment in pending_payments:
                    payment.status = PaymentStatus.CANCELLED.value
                    payment.updated_at = datetime.now()
                    logger.info(f"关闭订单相关的支付记录: 支付号={payment.payment_no}, 订单号={order.order_no}")
                
                db.commit()
                cancelled_count += 1
                
                # 发送订单取消通知
                notify_order_status_change(
                    user_id=order.user_id,
                    order_id=order.id,
                    order_no=order.order_no,
                    old_status=old_status,
                    new_status="cancelled",
                    amount=order.total_amount
                )
                
                logger.info(
                    f"自动取消超时订单: 订单号={order.order_no}, "
                    f"用户ID={order.user_id}, 创建时间={order.created_at}, "
                    f"超时时间={datetime.now() - order.created_at}, "
                    f"同时关闭了 {len(pending_payments)} 个支付记录"
                )
            except Exception as e:
                logger.error(
                    f"取消订单失败: 订单号={order.order_no}, 错误: {e}",
                    exc_info=True
                )
                db.rollback()
        
        if cancelled_count > 0:
            logger.info(f"自动取消超时订单完成，共取消 {cancelled_count} 个订单")
        else:
            logger.debug("未发现需要取消的超时订单")
            
    except Exception as e:
        logger.error(f"检查超时订单异常: {e}", exc_info=True)
        db.rollback()
    finally:
        db.close()

